﻿using InParkRedemptionAPI.DataAccess;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Internal;
using RapidSalesAdminPortalAPI.DataAccess;
using WebAPI.Common;
using WebAPI.Common.Attributes;
using WebAPI.DataAccess;
using WebAPI.Models;
using WebAPI.Util;

namespace WebAPI.Controllers
{

        ////[Authorize]
    //[Route("api/[controller]")]
    //[ApiController]
    //public class FrIpModuleController : ParentController
    //{
    //    private readonly RS_AdmPortalContext _context;
    //    private readonly IConfiguration _configuration;
    //    private readonly ILogUtility _logUtility;
    //    private readonly ILogger _logger;
    //    private readonly IDataProtectorUtility _dataProtectorUntility;
    //    public FrIpModuleController(RS_AdmPortalContext context, IConfiguration configuration, ILogUtility logUtility, ILogger<FrIpModuleController> logger, IDataProtectorUtility dataProtectorUntility)
    //    {
    //        _context = context;
    //        _configuration = configuration;
    //        _logUtility = logUtility; // sample code for DI of common utility class
    //        _logger = logger;
    //        _dataProtectorUntility = dataProtectorUntility;
    //    }

    //    [HttpPost("ModuleList")]
    //    public async Task<ActionResult<ResultMsg>> ModuleList([FromBody] ModuleListRequest et)
    //    {
    //        var resultMsg = new ResultMsg();
    //        IQueryable<FrIpModule> paComont = _context.FrIpModules.AsQueryable();

    //        if (!string.IsNullOrWhiteSpace(et.ModuleName))
    //            paComont = paComont.Where(x => x.ModuleName.Contains(et.ModuleName));

    //        if (!string.IsNullOrWhiteSpace(et.Description))
    //            paComont = paComont.Where(x => x.Description.Contains(et.Description));

    //        if (!string.IsNullOrWhiteSpace(et.Enable))
    //            paComont = paComont.Where(x => x.Enable == Convert.ToBoolean(et.Enable));

    //        if (et.isParent)
    //            paComont = paComont.Where(x => x.ParentId == 0);
    //        else
    //            paComont = paComont.Where(x => x.ParentId > 0);

    //        var paData = paComont.ToList().Select(pa => new ModuleListResponse()
    //        {
    //            Id = pa.Id,
    //            ModuleName = pa.ModuleName,
    //            Description = pa.Description,
    //            ParentId = pa.ParentId,
    //            Enable = pa.Enable,
    //            CreateDate = pa.CreateDate.ToString("yyyy-MM-dd HH:mm:ss"),
    //            UpdateDate = pa.UpdateDate.ToString("yyyy-MM-dd HH:mm:ss"),
    //            CreateUser = UserNameQuery(pa.CreateUser),
    //            UpdateUser = UserNameQuery(pa.UpdateUser)
    //        }).AsQueryable();

    //        if (!string.IsNullOrWhiteSpace(et.Field) && paComont.Count() > 0)
    //            paData = DBHelper.DataSorting(paData, et.Field, et.Order);
    //        else
    //            paData = DBHelper.DataSorting(paData, "CreateDate", "desc");

    //        var moduleList = await BasePageOutputExtensions.ToPagedListAsync(paData.ToList(), et.Page, et.PageSize);
    //        if (moduleList != null && moduleList.Total > 0 && !et.isParent) {
    //            var childList = moduleList.Items.Where(it => it.ParentId > 0).Select(x => x.Id).ToList();
    //            var perentList = _context.FrIpModules.Where(it => it.ParentId == 0).Select(x => new { Id = x.Id , Name = x.ModuleName}).ToList();
    //            foreach (var item in moduleList.Items)
    //            {
    //                item.ParentModuleName = perentList.FirstOrDefault(x => x.Id == item.ParentId)?.Name;
    //            }
    //        }

    //        return resultMsg.SetResultMsg(
    //             (int)ResultCode.Success,
    //             HelperUtility.GetDescription(ResultCode.Success),
    //             moduleList);
    //    }

    //    [HttpGet("{id}")]
    //    public async Task<ActionResult<ResultMsg>> ModuleById(int id)
    //    {
    //        var resultMsg = new ResultMsg();
    //        try
    //        {
    //            var pa = _context.FrIpModules
    //                .FirstOrDefault(x => x.Id == id);
    //            if (pa == null)
    //            {
    //                return resultMsg.SetResultMsg(
    //                     (int)ResultCode.NoDataFound,
    //                     HelperUtility.GetDescription(ResultCode.NoDataFound),
    //                     null);
    //            }

    //            var parent = _context.FrIpModules.FirstOrDefault(x => x.Id == pa.ParentId);
    //            var module = new ModuleListResponse()
    //            {
    //                Id = pa.Id,
    //                ModuleName = pa.ModuleName,
    //                ParentModuleName = parent == null ? "" : parent.ModuleName,
    //                Description = pa.Description,
    //                ParentId = pa.ParentId,
    //                Enable = pa.Enable,
    //                CreateDate = pa.CreateDate.ToString("yyyy-MM-dd HH:mm:ss"),
    //                UpdateDate = pa.UpdateDate.ToString("yyyy-MM-dd HH:mm:ss"),
    //                CreateUser = UserNameQuery(pa.CreateUser),
    //                UpdateUser = UserNameQuery(pa.UpdateUser)
    //            };
    //            return resultMsg.SetResultMsg(
    //                 (int)ResultCode.Success,
    //                 HelperUtility.GetDescription(ResultCode.Success),
    //                 module);
    //        }
    //        catch (Exception ex)
    //        {
    //            _logger.LogError(ex.Message);
    //            return resultMsg.SetResultMsg(
    //                 (int)ResultCode.ErrorOnRequestUnMarshalling,
    //                 HelperUtility.GetDescription(ResultCode.UserNotFound),
    //                 null);
    //        }
    //    }

    //    [HttpPost("ModuleListByParentId")]
    //    public async Task<ActionResult<ResultMsg>> ModuleListByParentId(int parentId)
    //    {
    //        var resultMsg = new ResultMsg();
    //        try
    //        {
    //            List<FrIpModule> list = await _context.FrIpModules.Where(x => x.ParentId == parentId).ToListAsync();
    //            if (list == null || list.Count <= 0)
    //            {
    //                return resultMsg.SetResultMsg(
    //                     (int)ResultCode.NoDataFound,
    //                     HelperUtility.GetDescription(ResultCode.NoDataFound),
    //                     null);
    //            }

    //            var moduleList = list.Select(pa=>new ModuleListByParentIdResponse
    //            {
    //                Id = pa.Id,
    //                ModuleName = pa.ModuleName,
    //            }).ToList();
    //            return resultMsg.SetResultMsg(
    //                 (int)ResultCode.Success,
    //                 HelperUtility.GetDescription(ResultCode.Success),
    //                 moduleList);
    //        }
    //        catch (Exception ex)
    //        {
    //            _logger.LogError(ex.Message);
    //            return resultMsg.SetResultMsg(
    //                 (int)ResultCode.ErrorOnRequestUnMarshalling,
    //                 HelperUtility.GetDescription(ResultCode.UserNotFound),
    //                 null);
    //        }
    //    }


    //    [Log("FrIpModule", "DeleteFrIpModule", description: "FrIpModule/DeleteFrIpModule", LogType: Enums.LogType.AdministratorAccountLog)]
    //    [HttpDelete("DeleteFrIpModule")]
    //    public async Task<ActionResult<ResultMsg>> DeleteFrIpModule(int id)
    //    {
    //        var resultMsg = new ResultMsg();
    //        var module = await _context.FrIpModules.FindAsync(id);

    //        if (module == null)
    //        {
    //            return resultMsg.SetResultMsg(
    //            (int)ResultCode.NotFound,
    //            HelperUtility.GetDescription(ResultCode.NotFound),
    //            null);
    //        }
    //        _context.Entry(module).State = EntityState.Deleted;
    //        _context.SaveChanges();
    //        return resultMsg.SetResultMsg(
    //            (int)ResultCode.Success,
    //            HelperUtility.GetDescription(ResultCode.Success),
    //            null);
    //    }

    //    [Log("FrIpModule", "InsertFrIpModule", description: "FrIpModule/InsertFrIpModule", LogType: Enums.LogType.AdministratorAccountLog)]
    //    [HttpPost("InsertFrIpModule")]
    //    public async Task<ActionResult<ResultMsg>> InsertFrIpModule([FromBody] InsertFrIpModuleRequest requestModel)
    //    {
    //        var resultMsg = new ResultMsg();
    //        try
    //        {
    //            if (ModuleExists(requestModel.ParentId, requestModel.ModuleName))
    //            {
    //                return resultMsg.SetResultMsg(
    //               (int)ResultCode.DataAlreadyExists,
    //               HelperUtility.GetDescription(ResultCode.DataAlreadyExists),
    //               null);
    //            }
    //            FrIpModule module = new FrIpModule();
    //            module.ModuleName = requestModel.ModuleName;
    //            module.Description = requestModel.Description;
    //            module.ParentId= requestModel.ParentId;
    //            module.Enable = requestModel.Enable;
    //            module.CreateDate = DateTime.Now;
    //            module.UpdateDate = DateTime.Now;
    //            module.CreateUser = CurrentUserId;
    //            module.UpdateUser = CurrentUserId;
    //            _context.Entry(module).State = EntityState.Added;
    //            await _context.SaveChangesAsync();

    //            return resultMsg.SetResultMsg(
    //            (int)ResultCode.Success,
    //            HelperUtility.GetDescription(ResultCode.Success), 
    //            null);
    //        }
    //        catch (Exception ex)
    //        {
    //            _logger.LogError(ex.Message);
    //            return resultMsg.SetResultMsg(
    //             (int)ResultCode.ErrorOnRequestUnMarshalling,
    //             HelperUtility.GetDescription(ResultCode.ErrorOnRequestUnMarshalling),
    //             null);
    //        }
    //    }

    //    [Log("FrIpModule", "UpdateFrIpModule", description: "FrIpModule/UpdateFrIpModule", LogType: Enums.LogType.AdministratorAccountLog)]
    //    [HttpPost("UpdateFrIpModule")]
    //    public async Task<ActionResult<ResultMsg>> UpdateFrIpModule([FromBody] UpdateFrIpModuleRequest requestModel)
    //    {
    //        var resultMsg = new ResultMsg();
    //        try
    //        {
    //            var module = await _context.FrIpModules.FirstOrDefaultAsync(x => x.Id == requestModel.Id);
    //            if (module == null)
    //                return resultMsg.SetResultMsg( (int)ResultCode.NotFound, HelperUtility.GetDescription(ResultCode.NotFound), null);

    //            if (!module.ModuleName.Equals(requestModel.ModuleName) && ModuleExists(requestModel.ParentId, requestModel.ModuleName))
    //            {
    //                return resultMsg.SetResultMsg(
    //               (int)ResultCode.DataAlreadyExists,
    //               HelperUtility.GetDescription(ResultCode.DataAlreadyExists),
    //               null);
    //            }

    //            module.ModuleName = requestModel.ModuleName;
    //            module.Description = requestModel.Description;
    //            module.ParentId = requestModel.ParentId;
    //            module.Enable = requestModel.Enable;
    //            module.UpdateDate = DateTime.Now;
    //            module.UpdateUser = CurrentUserId;
    //            _context.Entry(module).State = EntityState.Modified;


    //            List<FrIpDataDictionary> dicDataList = null;
    //            FrIpModule model = null;
    //            if (requestModel.ParentId > 0)
    //            {
    //                model = _context.FrIpModules.First(x => x.Id == requestModel.ParentId);
    //                dicDataList = _context.FrIpDataDictionaries.AsQueryable().Where(x => x.CodeItemId == requestModel.ParentId.ToString()
    //                && x.ItemTypeId == requestModel.Id.ToString()).ToList();
    //            }

    //            else {
    //                dicDataList = _context.FrIpDataDictionaries.AsQueryable().Where(x => x.CodeItemId == requestModel.Id.ToString()).ToList();
    //            }
    //            if (dicDataList != null && dicDataList.Count > 0) {
    //                foreach (var item in dicDataList)
    //                {
    //                    if (requestModel.ParentId == 0)
    //                    {
    //                        item.CodeItemName = requestModel.ModuleName;
    //                    }
    //                    else { 
    //                        item.ItemTypeName = requestModel.ModuleName;
    //                        if (model!=null) { 
    //                            item.CodeItemName = model.ModuleName;
    //                        }
    //                    }
    //                }
    //            }

    //            await _context.SaveChangesAsync();

    //            return resultMsg.SetResultMsg(
    //            (int)ResultCode.Success,
    //            HelperUtility.GetDescription(ResultCode.Success),
    //            null);
    //        }
    //        catch (Exception ex)
    //        {
    //            _logger.LogError(ex.Message);
    //            return resultMsg.SetResultMsg(
    //             (int)ResultCode.ErrorOnRequestUnMarshalling,
    //             HelperUtility.GetDescription(ResultCode.ErrorOnRequestUnMarshalling),
    //             null);
    //        }
    //    }

    //    [Log("FrIpModule", "EnableFrIpModule", description: "FrIpModule/EnableFrIpModule", LogType: Enums.LogType.AdministratorAccountLog)]
    //    [HttpPut("EnableFrIpModule")]
    //    public async Task<ActionResult<ResultMsg>> EnableFrIpModule([FromBody] EnableFrIpModuleRequest requestModel)
    //    {
    //        ResultMsg resultMsg = new();
    //        requestModel.ids = "," + requestModel.ids + ",";
    //        var moduleList = _context.FrIpModules.Where(x => requestModel.ids.Contains(","+x.Id.ToString()+ ",")).ToList();
    //        if (moduleList == null || moduleList.Count <= 0)
    //        {
    //            return resultMsg.SetResultMsg(
    //           (int)ResultCode.NoDataFound,
    //           HelperUtility.GetDescription(ResultCode.NoDataFound),
    //           null);
    //        }
    //        foreach (var module in moduleList)
    //        {
    //            module.Enable = requestModel.enable;
    //        }
    //        await _context.SaveChangesAsync();
    //        return resultMsg.SetResultMsg(
    //            (int)ResultCode.Success,
    //            HelperUtility.GetDescription(ResultCode.Success),
    //            null);
    //    }

    //    [NonAction]
    //    public string UserNameQuery(Guid id)
    //    {
    //        FrIpAdministratorAccount dt = _context.FrIpAdministratorAccounts?.FirstOrDefault(x => x.Id.Equals(id));
    //        return dt?.AccountName ?? "";
    //    }

    //    [NonAction]
    //    public bool ModuleExists(int parentId, string moduleName)
    //    {
    //        return _context.FrIpModules.Any(x => x.ModuleName == moduleName && x.ParentId == parentId);
    //    }}
}
